import { ref, onUnmounted } from 'vue';

/**
 * 一个通用的WebSocket连接Composables
 * @param {string} url - WebSocket服务器的完整地址
 */
export function useWebSocket(url) {
    const data = ref(null);
    const status = ref('CLOSED'); // 'CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'
    const ws = ref(null);

    const connect = () => {
        if (status.value === 'OPEN' || status.value === 'CONNECTING') return;

        status.value = 'CONNECTING';
        ws.value = new WebSocket(url);

        ws.value.onopen = () => {
            status.value = 'OPEN';
            console.log('WebSocket connected');
        };

        ws.value.onmessage = (event) => {
            try {
                // 假设服务器发送的是JSON字符串
                data.value = JSON.parse(event.data);
            } catch (e) {
                data.value = event.data; // 如果不是JSON，则直接赋值
            }
        };

        ws.value.onclose = () => {
            status.value = 'CLOSED';
            ws.value = null;
            console.log('WebSocket disconnected');
        };

        ws.value.onerror = (error) => {
            console.error('WebSocket error:', error);
            status.value = 'CLOSED';
        };
    };

    const send = (payload) => {
        if (ws.value && ws.value.readyState === WebSocket.OPEN) {
            ws.value.send(JSON.stringify(payload));
        } else {
            console.warn('WebSocket is not connected.');
        }
    };

    const close = () => {
        if (ws.value) {
            ws.value.close();
        }
    };

    // 组件卸载时自动关闭连接
    onUnmounted(() => {
        close();
    });

    return {
        data,
        status,
        connect,
        send,
        close,
    };
}